﻿using System;
using System.Threading;
using static PengSW.RuntimeLog.RL;

namespace PengSW.TimerTaskHelper
{
    public class TimerTask
    {
        public TimerTask(TimeSpan aInterval, Action aAction, string aDescription)
        {
            _Interval = aInterval;
            Description = aDescription;
            _Timer = new Timer(new TimerCallback(OnTimer), aAction, aInterval, TimeSpan.Zero);
        }

        private bool _IsRunning = false;
        private void OnTimer(object aAction)
        {
            _IsRunning = true;
            try
            {
                (aAction as Action)();
            }
            catch (Exception ex)
            {
                L($"{Description}：{ex.Message}");
            }
            finally
            {
                Stop();
                _IsRunning = false;
            }
        }

        public void Reset()
        {
            if (!_IsRunning) _Timer.Change(_Interval, TimeSpan.Zero);
        }

        public void Stop()
        {
            try
            {
                TimerTaskManager.RemoveTask(this);
                _Timer.Change(-1, 0);
                _Timer.Dispose();
            }
            catch
            {
            }
        }

        public string Description { get; private set; }
        private Timer _Timer;
        private TimeSpan _Interval;
    }
}
